#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define BUFFER_SIZE 1024

void error_handling(char *message);

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <username:password@IP:port>\n", argv[0]);
        exit(1);
    }

    char *param = argv[1];

    // 解析参数
    char username[50], password[50], ip[50];
    int port;

    sscanf(param, "%[^:]:%[^@]@%[^:]:%d", username, password, ip, &port);

    // 创建套接字
    int sock = socket(PF_INET, SOCK_STREAM, 0);
    if (sock == -1)
        error_handling("socket() error");

    // 设置服务器信息
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(ip);
    server_addr.sin_port = htons(port);

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
        error_handling("connect() error");

    // 发送认证信息
    char auth_msg[BUFFER_SIZE];
    sprintf(auth_msg, "Authentication: %s:%s", username, password);
    write(sock, auth_msg, strlen(auth_msg));

    // 接收认证结果
    char auth_result[BUFFER_SIZE];
    read(sock, auth_result, sizeof(auth_result));

    if (strcmp(auth_result, "Authentication successful") != 0) {
        printf("Authentication failed: %s\n", auth_result);
        close(sock);
        exit(1);
    }

    // 认证成功，进行聊天
    printf("认证成功，进行聊天!\n");

    while (1) {
        char message[BUFFER_SIZE];
        printf("自己: ");
        fgets(message, sizeof(message), stdin);

        // 发送消息
        write(sock, message, strlen(message));

        // 接收对方消息
        read(sock, message, sizeof(message));
        printf("朋友: %s", message);
    }

    close(sock);
    return 0;
}

void error_handling(char *message) {
    perror(message);
    exit(1);
}
